﻿using Fast2Jenkins.Helper;
using Fast2Jenkins.Jenkins;
using Jenkins.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jenkins.UI
{
    public sealed class JenkinsDataSource
    {
        private static JenkinsDataSource datasource = new JenkinsDataSource();

        private ObservableCollection<JenkinsViewDataGroup> groups = new ObservableCollection<JenkinsViewDataGroup>();
        public ObservableCollection<JenkinsViewDataGroup> AllGroups
        {
            get { return this.groups; }
        }

        public static IEnumerable<JenkinsViewDataGroup> GetGroups(string uniqueId)
        {
            if (!uniqueId.Equals("AllGroups")) throw new ArgumentException("Only 'AllGroups' is supported as a collection of groups");

            return datasource.AllGroups;
        }

        public static JenkinsViewDataGroup GetGroup(string uniqueId)
        {
            var matches = datasource.AllGroups.Where((group) => group.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        public static JenkinsJobDataItem GetItem(string uniqueId)
        {
            var matches = datasource.AllGroups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        public JenkinsDataSource()
        {
            PopulateAsync();
        }

        private async void PopulateAsync()
        {
            int generatedID = 0;

            var items = await JenkinsParser.Parse("", "", "");
            foreach (var keyValue in items)
            {
                var view = keyValue.Key;
                var group = new JenkinsViewDataGroup(generatedID++ + "", view.Name, "", view.Url, "");

                var jobs = keyValue.Value;
                foreach (Job job in jobs)
                {
                    group.Items.Add(new JenkinsJobDataItem(generatedID++ + "", job.Name, "", "", job.Url, job.Color, group));
                }

                AllGroups.Add(group);
            }
        }
    }
}
